package assignment.day3;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet(description = "Day3 Assignments2 ProductServlet", urlPatterns = { "/D3A2ProductServlet" })
public class D3A2ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.write("<html><head><title>Categories</title></head><body bgcolor='lavender'>");
		try {
			/*
			 * Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con
			 * = DriverManager.getConnection(
			 * "jdbc:oracle:thin:@10.23.0.100:1521:esgdb10", "scott", "tiger");
			 */

			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("jdbc/mydata");
			Connection con = ds.getConnection();

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select * from products where id="
					+ request.getParameter("category"));
			out.write("<table border='2'>");
			while (rs.next()) {
				out.write("<tr><td>");
				out.write(rs.getString(2));
				out.write("</td><td> ");
				out.write(rs.getString(3));
				out.write("</td><td> ");
				out.write(rs.getString(4));
				out.write("</td></tr>");
			}
			out.write("</table>");
			stmt.close();
			con.close();
		} catch (Exception e) {
			out.write(e.toString());
		}
		out.write("</body></html>");
	}
}
